package com.itheima.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        String requestURI = request1.getRequestURI();
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};
        boolean check = check(requestURI, urls);
        if (check){
            chain.doFilter(request1,response1);
            return;
        }
        if (request1.getSession().getAttribute("employee")!=null){//如果session存在数据，将会一直被放行数据而不会再次跳回登陆页面。
            HttpSession session = request1.getSession();
            Long id = (Long) session.getAttribute("employee");
            BaseContext.setCurrentId(id);
            chain.doFilter(request1,response1);
            return;
        }
        HttpSession session = request1.getSession();
        Long userid = (Long) session.getAttribute("user");
        if (userid!=null){
            BaseContext.setCurrentId(userid);
            chain.doFilter(request1,response1);
            return;
        }

        response1.setContentType("text/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(R.error("NOTLOGIN"));
        response1.getWriter().write(s);//配合前端的js代码使页面跳转到登录页面，如果所有路径被拦截会导致一直在页面上写入json
        /*前端代码
  // 响应拦截器
  service.interceptors.response.use(res => {
      if (res.data.code === 0 && res.data.msg === 'NOTLOGIN') {// 返回登录页面
        console.log('---/backend/page/login/login.html---')
        localStorage.removeItem('userInfo')
        window.top.location.href = '/backend/page/login/login.html'
      } else {
        return res.data
      }
    },*/
    }
    public boolean check(String requestURL,String[] urls){//校验通配符，返回boolean类型的数据

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url,requestURL);
            if (match==true){
                return true;
            }
        }
        return false;
    }
}
